﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using HtmlAgilityPack;
using System.IO;

using DSUltimate.Parsers;
using DSUltimate.Manager;
using DSUltimate.ImageEdit;

namespace DSUltimate
{
    public partial class MainForm : Form
    {
        public WorkSheet activeWorkSheet;

        //Amazon
        private AmazonParser amazonParser;
        private AmazonParserSettings amazonParserSettings;



        private string[] PlaceHolders = { "MAIN_KEYWORDS_HERE", "TITLE_HERE", "BULLET_POINTS_HERE", "DESCRIPTION_HERE", "PHOTO_BUCKET_LINK_HERE", "KEYWORDS_HERE" };

        public DSDTitleBuilder titleBuilder;
        public List<Listing> Listings;
      //  public List<Image> LargeImages;


        private Image ActiveImage;
        private Image Logo = null;

        public MainForm()
        {
            InitializeComponent();
          
        }

        private void UpdateStatus(string message)
        {
            statusLabel.Text = message;
            if (statusLabel.BackColor == Color.Red)
            {
                statusLabel.BackColor = Color.Cyan;
            }
            else
            {
                statusLabel.BackColor = Color.Red;
            }
            
            statusLabel.Invalidate();
            this.Update();
        }

        private void loadBtn_Click(object sender, EventArgs e)
        {
            //Check if Item already exists by ASIN
            amazonParser = new AmazonParser(amazonParserSettings);
            UpdateStatus("Downloading HTML Data");
            AmazonItemDetailed amazonItem = amazonParser.GetAmazonItemDetailed(urlTextBox.Text);
            UpdateStatus("Done");
            activeWorkSheet.AddAmazonItemDetailed(amazonItem);
            amazonItemsComboBox.Items.Add(amazonItem.Title);
            amazonItemsComboBox.SelectedIndex = amazonItemsComboBox.Items.Count - 1;
        }

        private AmazonItemDetailed GetActiveAmazonItemDetailed(string amazonTitle)
        {
            string activeAmazonItemTitle = amazonTitle;
            return (AmazonItemDetailed)(from item in activeWorkSheet.GetAmazonItemsDetailed()
                                                                 where item.Title == activeAmazonItemTitle
                                                                 select item).First();
        }
        private Listing GetActiveListing(string amazonTitle)
        {
            string activeAmazonItemTitle = amazonTitle;
            return (Listing)(from item in activeWorkSheet.GetListings()
                                        where item.AmazonTitle == activeAmazonItemTitle
                                        select item).First();
        }

        private void ParseDataTabUpdate()
        {
            AmazonItemDetailed amazonItem = GetActiveAmazonItemDetailed(amazonItemsComboBox.SelectedItem.ToString());

            ClearParseDataTabWindows();
            ShowAmazonTitle(amazonItem);
            ShowAmazonBullets(amazonItem);
            ShowAmazonDescription(amazonItem);
            ShowAmazonImages(amazonItem); 
        }

        private void ClearParseDataTabWindows()
        {
            amazonTitleTextBox.Text = "";
            bulletsTextBox.Text = "";
            descriptionTextBox.Text = "";
            imageListView.Clear();
            imageList.Images.Clear();
        }
        private void ShowAmazonTitle(AmazonItemDetailed amazonItem)
        {
            amazonTitleTextBox.Text = amazonItem.Title;
        }
        private void ShowAmazonBullets(AmazonItemDetailed amazonItem)
        {
            bulletsTextBox.Text = amazonItem.BulletPoints;
        }
        private void ShowAmazonDescription(AmazonItemDetailed amazonItem)
        {
            descriptionTextBox.Text = amazonItem.ItemDescription;
        }
        private void ShowAmazonImages(AmazonItemDetailed amazonItem)
        {
            imageListView.Clear();
            imageList.Images.Clear();

            for (int i = 0; i < amazonItem.Images.Count; i++)
            {
                imageList.Images.Add(amazonItem.Images[i]);
                ListViewItem pic = new ListViewItem();
                pic.ImageIndex = i;
                pic.Text = string.Format("{0}px x {1}px", amazonItem.Images[i].Size.Width, amazonItem.Images[i].Size.Height);
                imageListView.Items.Add(pic);
            }
        }


        private void button1_Click(object sender, EventArgs e)
        {
            addImageFileDialog.ShowDialog();
        }

        private void addImageFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            AmazonItemDetailed amazonItem = GetActiveAmazonItemDetailed(amazonItemsComboBox.SelectedItem.ToString());

            string[] paths = addImageFileDialog.FileNames;
            for (int i = 0; i < paths.Length; i++)
            {
                amazonItem.Images.Add(Image.FromFile(paths[i]));
            }
            ShowAmazonImages(amazonItem);
        }


        private void addListingBtn_Click(object sender, EventArgs e)
        {
            AmazonItemDetailed amazonItem = GetActiveAmazonItemDetailed(amazonItemsComboBox.SelectedItem.ToString());
            Listing currentListing = new Listing();

            currentListing.AmazonTitle = amazonTitleTextBox.Text;
            currentListing.ItemDescription = descriptionTextBox.Text;

            string[] bullets = bulletsTextBox.Text.Split('\n');
            List<string> bulletsToSave = new List<string>();
            for (int i = 0; i < bullets.Length; i++)
            {
                if (bullets[i].Length > 2)
                {
                    bulletsToSave.Add(bullets[i]);
                }
            }
            currentListing.BulletPoints = bulletsToSave;


            List<Image> selectedImages = new List<Image>();
            ListView.CheckedIndexCollection indexes = imageListView.CheckedIndices;
            foreach (int i in indexes)
            {
                selectedImages.Add(amazonItem.Images[i]);
            }
            currentListing.Images = selectedImages;

            //Check if listing already exists
            var sameListings =
                from list in activeWorkSheet.GetListings()
                where list.AmazonTitle == currentListing.AmazonTitle
                select list;


            if (sameListings.ToList<Listing>().Count == 0) 
            {
                //Add New Listing
                activeWorkSheet.AddListing(currentListing);
                MessageBox.Show("Listing Added Succesfully!");
            }
            else
            {
                //Update old listing 
                DialogResult dialogResult = MessageBox.Show("Listing with the same Amazon title already exists! Would you like to update it?", "Same Listing", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                      int indexToInsert = activeWorkSheet.GetListings().IndexOf(sameListings.ToList<Listing>()[0]);
                      activeWorkSheet.RemoveListing(sameListings.ToList<Listing>()[0]);
                      activeWorkSheet.InsertListing(indexToInsert, currentListing); //Might be unnecessery!!!! FIX
                      MessageBox.Show("Listing Updated Succesfully!");
                }     
            }
        }

        private void imageEditTabPage_Enter(object sender, EventArgs e)
        {
            foreach (Listing item in activeWorkSheet.GetListings())
            {
                listingsComboBox.Items.Add(item.AmazonTitle);
            }
            if(listingsComboBox.Items.Count > 0)
            {
                listingsComboBox.SelectedIndex = 0;
            }
        }

        private void listingsComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateImagesInImageEditTab();
            UpdateActiveImage(0);
        }

        private void UpdateActiveImage(int imageIndex)
        {
            Image actImg = GetActiveListing(listingsComboBox.SelectedItem.ToString()).Images[imageIndex];
            imagePictureBox.Image = actImg;
            ActiveImage = actImg;
        }
        private void UpdateImagesInImageEditTab()
        {
            //Update images in image edit tab page
            Listing activeListing = GetActiveListing(listingsComboBox.SelectedItem.ToString());
            selectedImagesList.Images.Clear();
            selectedImagesListView.Items.Clear();
            for (int i = 0; i < activeListing.Images.Count; i++)
            {
                selectedImagesList.Images.Add(activeListing.Images[i]);
                ListViewItem pic = new ListViewItem();
                pic.ImageIndex = i;
                pic.Text = string.Format("{0}px x {1}px", activeListing.Images[i].Size.Width, activeListing.Images[i].Size.Height);
                selectedImagesListView.Items.Add(pic);
            }      
        }


        private void selectedImagesListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            UpdateActiveImage(e.ItemIndex);
        }

        private Image_Settings GetSettings()
        {
            LogoPosition position = LogoPosition.BottomRight;
            if (brandCheckBox.Checked)
            {             
                switch (logoPositionComboBox.SelectedItem.ToString())
                {
                    case "Top Right":
                        position = LogoPosition.TopRight;
                        break;
                    case "Bottom Right":
                        position = LogoPosition.BottomRight;
                        break;
                    case "Top Left":
                        position = LogoPosition.TopLeft;
                        break;
                    case "Bottom Left":
                        position = LogoPosition.BottomLeft;
                        break;
                    default:
                        position = LogoPosition.TopRight;
                        break;
                }
            }
            Image_Settings settings = new Image_Settings(
                    Convert.ToInt32(widthTextBox.Text),
                    Convert.ToInt32(heightTextBox.Text),
                    brandCheckBox.Checked,
                    position); 
            if (brandCheckBox.Checked)
            {
                if (Logo != null)
                {
                    settings.Logo = Logo;
                    settings.LogoWidth = Convert.ToInt32(logoWidthTextBox.Text);
                    settings.LogoHeight = Convert.ToInt32(logoHeightTextBox.Text);
                }
                else
                {
                    //Ask to load logo
                    MessageBox.Show("No logo image found. Items will not be branded!");
                }
            }

            return settings;
        }

        private void applyBtn_Click(object sender, EventArgs e)
        {
            Image_Settings settings = GetSettings();

            ImageEditor editor = new ImageEditor(settings, ActiveImage); //Amazon image
            Image newImg = editor.ApplySettings()[0];
            Listing activeListing = Listings[listingsComboBox.SelectedIndex];
            int positionToInsert = activeListing.Images.IndexOf(ActiveImage);
            activeListing.Images.Remove(ActiveImage);
            activeListing.Images.Insert(positionToInsert, newImg);
            UpdateImagesInImageEditTab();
            imagePictureBox.Image = newImg;
            ActiveImage = newImg;
        }

        private void applyToAllBtn_Click(object sender, EventArgs e)
        {
            Image_Settings settings = GetSettings();

            ImageEditor editor = new ImageEditor(settings, Listings[listingsComboBox.SelectedIndex].Images);
            List<Image> newImgs = editor.ApplySettings();
            Listings[listingsComboBox.SelectedIndex].Images = newImgs;
            //FIX for all images
            UpdateImagesInImageEditTab();
            imagePictureBox.Image = Listings[listingsComboBox.SelectedIndex].Images[0];
        }

        private void applyToAllListings_Click(object sender, EventArgs e)
        {
            Image_Settings settings = GetSettings();

            ImageEditor editor;

            for (int i = 0; i < Listings.Count; i++)
            {
                editor = new ImageEditor(settings, Listings[i].Images);
                List<Image> newImgs = editor.ApplySettings();
                Listings[i].Images = newImgs;
            }

            UpdateImagesInImageEditTab();
            imagePictureBox.Image = Listings[listingsComboBox.SelectedIndex].Images[0];
        }

        private void browseLogoBtn_Click(object sender, EventArgs e)
        {
            logoSelectionDialog.ShowDialog();
        }

        private void logoSelectionDialog_FileOk(object sender, CancelEventArgs e)
        {
            Logo = Image.FromFile(logoSelectionDialog.FileName);
        }

        private void brandCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (!brandCheckBox.Checked)
            {
                Logo = null;
            }
        }

        private void saveImageNameBtn_Click(object sender, EventArgs e)
        {
            string name = firstWordImageName.Text + "-" + secondWordImageName.Text + "-" + thirdWordImageName.Text;
            ItemImage pic = new ItemImage(ActiveImage, name, PictureType.Ebay);
          //  pic.SavePicture(Listings[listingsComboBox.SelectedIndex].Title);
            MessageBox.Show(string.Format("{0}.jpg Saved!",name));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            templateLoadDialog.ShowDialog();
        }

        private void templateLoadDialog_FileOk(object sender, CancelEventArgs e)
        {
            StreamReader reader = new StreamReader(templateLoadDialog.FileName);
            string Template = reader.ReadToEnd();
            reader.Close();
            templeteTextBox.Text = Template;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            webBrowserScreen.DocumentText = templeteTextBox.Text;
        }

        private void templeteTextBox_TextChanged(object sender, EventArgs e)
        {
            webBrowserScreen.DocumentText = templeteTextBox.Text;
        }

        private void templateEditorPage_Enter(object sender, EventArgs e)
        {
            foreach (Listing item in Listings)
            {
                listingsComboBox1.Items.Add(item.AmazonTitle);
            }
            if (listingsComboBox.Items.Count > 0)
            {
                listingsComboBox1.SelectedIndex = 0;
            }
        }

        private void listingsComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void putDataInTemplBtn_Click(object sender, EventArgs e)
        {
            Listing activeListing = Listings[listingsComboBox1.SelectedIndex];
            string templete = templeteTextBox.Text;

            string bulletpoints = "";
            for (int i = 0; i < activeListing.BulletPoints.Count; i++)
			{
			    bulletpoints += string.Format("<li>{0}</li>",activeListing.BulletPoints[i]);
			}

            


            templete = templete.Replace(PlaceHolders[0], mainKeywordsTextBox.Text);
            templete = templete.Replace(PlaceHolders[1], activeListing.EbayTitle);
            templete = templete.Replace(PlaceHolders[2], bulletpoints);
            templete = templete.Replace(PlaceHolders[3], activeListing.ItemDescription);
            templete = templete.Replace(PlaceHolders[4], photoBucketLinkTextBox.Text);
            templete = templete.Replace(PlaceHolders[5], additionalKeywordsTextBox.Text);
            templeteTextBox.Text = templete;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://photobucket.com/");
        }

        private void resizeBrowserMenuItem_Click(object sender, EventArgs e)
        {
            if (webBrowserScreen.Dock == DockStyle.None)
            {
                webBrowserScreen.Dock = DockStyle.Fill;
                resizeBrowserMenuItem.Text = "Minimize";
                webBrowserScreen.BringToFront();
            }
            else
            {
                webBrowserScreen.Dock = DockStyle.None;
                resizeBrowserMenuItem.Text = "Maximize";
            }
        }

        private void descriptionTextBox_TextChanged(object sender, EventArgs e)
        {
            charCountLabel.Text = string.Format("Characters total: {0}",descriptionTextBox.Text.Length+bulletsTextBox.Text.Length);
        }

        private void bulletsTextBox_TextChanged(object sender, EventArgs e)
        {
            charCountLabel.Text = string.Format("Characters total: {0}", descriptionTextBox.Text.Length + bulletsTextBox.Text.Length);
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            charLeftLabel.Text = string.Format("{0} Characters Left",90 - ebayTitleTextBox.Text.Length);
        }

        private void overviewTabPage_Enter(object sender, EventArgs e)
        {
            for (int i = 0; i < Listings.Count; i++)
			{
			    finishedListingsListBox.Items.Add(Listings[i].AmazonTitle);
                finishedListingsListBox.SetItemChecked(i, true);
			}
        }

        private void titleTabPage_Enter(object sender, EventArgs e)
        {
            keywordsListBox.Items.Clear();
            if (Listings.Count > 0)
            {

                for (int i = 0; i < Listings.Count; i++)
                {
                    listingsComboBox3.Items.Add(Listings[i].AmazonTitle);
                }
                listingsComboBox3.SelectedIndex = 0;

                KeywordsAnalizer analizer = new KeywordsAnalizer();
                Dictionary<string, int> keywords = analizer.FindMostRepeatedKeywords(Listings[0].ItemDescription);
                foreach (var keyword in keywords)
                {
                    keywordsListBox.Items.Add(string.Format("{0} -> {1}", keyword.Key, keyword.Value));
                }
            }

        }

        private void listingsComboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            ebayTitleTextBox.Text = listingsComboBox3.SelectedItem.ToString();      
        }

        private void listingsComboBox0_SelectedIndexChanged(object sender, EventArgs e)
        {
            ParseDataTabUpdate();
        }

        private void titleBuilderDSDLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://dsdomination.com/members/show/titleBuilder");
        }

        private void dsdLoginBtn_Click(object sender, EventArgs e)
        {
            titleBuilder = new DSDTitleBuilder(usernameTextBox.Text, passwordTextBox.Text);
        }

        private void searchDSDKeywordsBtn_Click(object sender, EventArgs e)
        {
            dsdKeywordsListBox.Items.Clear();
            string[] keywords = titleBuilder.GetKeywords(DSDSearchTextBox.Text);
            dsdKeywordsListBox.Items.AddRange(keywords);
            
        }

        private void searchDSDKeywordsBtn2_Click(object sender, EventArgs e)
        {
            dsdKeywordsListBox2.Items.Clear();
            string[] keywords = titleBuilder.GetKeywords(DSDSearchTextBox2.Text);
            dsdKeywordsListBox2.Items.AddRange(keywords);
        }

        private void searchDSDKeywordsBtn3_Click(object sender, EventArgs e)
        {
            dsdKeywordsListBox3.Items.Clear();
            string[] keywords = titleBuilder.GetKeywords(DSDSearchTextBox3.Text);
            dsdKeywordsListBox3.Items.AddRange(keywords);
        }

        private void filterKeywordsCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < dsdKeywordsListBox.Items.Count; i++)
			{
                if (dsdKeywordsListBox.Items[i].ToString().Length < 4)
                {
                    dsdKeywordsListBox.Items.Remove(dsdKeywordsListBox.Items[i]);
                }
			 
			}

            for (int i = 0; i < dsdKeywordsListBox2.Items.Count; i++)
            {
                if (dsdKeywordsListBox2.Items[i].ToString().Length < 4)
                {
                    dsdKeywordsListBox2.Items.Remove(dsdKeywordsListBox2.Items[i]);
                }

            }

            for (int i = 0; i < dsdKeywordsListBox3.Items.Count; i++)
            {
                if (dsdKeywordsListBox3.Items[i].ToString().Length < 4)
                {
                    dsdKeywordsListBox3.Items.Remove(dsdKeywordsListBox3.Items[i]);
                }

            } 

            
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            EbayParser parser = new EbayParser();
            List<EbayItem> foundItems = parser.SearchForKeywords("cat");

            foreach (EbayItem item in foundItems)
            {
                richTextBox1.Text += item.PictureURL;
            
                richTextBox1.Text += "\n";
            }
        }

        //New Worksheet
        private void newWorksheetBtn_Click(object sender, EventArgs e)
        {
            activeWorkSheet = new WorkSheet("adsfadfs", GetWorksheetSettings());
            MessageBox.Show("Worksheet created succesful");
        }

        private Settings GetWorksheetSettings()
        {
            Settings currentSettings = new Settings();
            currentSettings.MainDirectory = mainDirectoryTextBox.Text;
            //Set all other settings
            return currentSettings;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            //inpput worksheet name
            activeWorkSheet = WorkSheet.Load("path");
            MessageBox.Show("Worksheet load succesful!");
        }


        //Init Parse Data Tab Page
        private void parseDataTabPage_Enter(object sender, EventArgs e)
        {
            amazonParserSettings = new AmazonParserSettings();
        }

        private void filterLargeCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            amazonParserSettings.FilterImages = filterLargeCheckBox.Checked;
        }

      



        

        



        
    }
}
